import 'package:sqflite/sqflite.dart';
import '../database/database_helper.dart';
import '../models/product.dart';

class ProductService {
  final dbHelper = DatabaseHelper.instance;

  Future<int> insertProduct(Product product) async {
    Database db = await dbHelper.database;
    return await db.insert('products', product.toMap());
  }

  Future<int> updateProduct(Product product) async {
    Database db = await dbHelper.database;
    return await db.update(
      'products',
      product.toMap(),
      where: 'id = ?',
      whereArgs: [product.id],
    );
  }

  Future<int> deleteProduct(int id) async {
    Database db = await dbHelper.database;
    return await db.delete(
      'products',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  Future<Product?> getProductById(int id) async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query(
      'products',
      where: 'id = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return Product.fromMap(maps.first);
    }
    return null;
  }

  Future<List<Product>> getAllProducts() async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query('products');
    return List.generate(maps.length, (i) => Product.fromMap(maps[i]));
  }

  // 减少商品库存
  Future<bool> decreaseStock(int productId, int quantity) async {
    Database db = await dbHelper.database;

    // 先获取当前商品
    Product? product = await getProductById(productId);
    if (product == null) {
      return false;
    }

    // 检查库存是否足够
    if (product.stock < quantity) {
      return false;
    }

    // 更新库存
    int newStock = product.stock - quantity;
    int result = await db.update(
      'products',
      {'stock': newStock},
      where: 'id = ?',
      whereArgs: [productId],
    );

    return result > 0;
  }
}
